//
//  SelectDishViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-9.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "EditOrderDishViewController.h"
#import "SelectDishLeftCell.h"
#import "SelectDishRightCell.h"
#import "EditSelectedDishViewController.h"
#import "PackagesViewController.h"
#import "CommUtil.h"

#define TITLE_WIDTH 140
#define TITLE_HEIGHT 200
#define TITLE_TEXT @"餐饮类型 精品涮"
#define CAT_FORMAT_TEXT @"餐饮类型 %@"
#define TOP_LOCATION CGRectMake(0, 0, 1, 1)

@interface EditOrderDishViewController()

@property (assign, nonatomic) BOOL isNext;

@end

@implementation EditOrderDishViewController

- (id)initWithShopId:(NSString*)shopId
{
    self = [super initWithNibClass:[EditOrderDishViewController class]];
    if (self) {
        self.shopId = shopId;
        _photoList = [[NSMutableArray alloc] initWithCapacity:5];
        _dataSource = [[EditOrderDishDataSource alloc] initWithVC:self];
        _selectedDishList = [[NSMutableArray alloc] initWithCapacity:10];
        _orderDishList = [[NSMutableArray alloc] initWithCapacity:10];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    
    [_dataSource fetchDishCategories];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate sharedInstance] hideTabBar:self.tabBarController];
}

- (void)setupUI
{
    [self createLeftButton];
    self.navigationItem.titleView = _titleButton;
    
    _selectCategoriesView = [[EditOrderDishCategoriesView alloc] initWithFrame:CGRectMake((ScreenWidth-TITLE_WIDTH)/2, -TITLE_HEIGHT, TITLE_WIDTH, TITLE_HEIGHT)];
    _selectCategoriesView.delegate = self;
    [self.view addSubview:_selectCategoriesView];
    
    _leftTable.dataSource = _rightTable.dataSource = _dataSource;
    _leftTable.delegate = _rightTable.delegate = _dataSource;
    
    _leftTable.top = 0;
    _rightTable.height = ScreenHeight-NavBarHeight-StatusBarHeight- _footerView.height;
    _leftTable.height = _rightTable.height + NavBarHeight + StatusBarHeight+1;
    _footerView.top = _leftTable.bottom;
    [_leftTable drawBorder];
}

- (void)rightButtonClick:(id)sender
{
    PackagesViewController *packagesVC = [[PackagesViewController alloc] initWithShopId:_shopId];
    [self.navigationController pushViewController:packagesVC animated:YES];
}

- (IBAction)selectCategoriesAction:(id)sender
{
    [_selectCategoriesView showOrVisible];
}

- (void)selectDishCatFinished:(NSDictionary *)dic
{
    NSString *catId = [dic objectForKey:@"id"];
    NSString *catName = [dic objectForKey:@"lbname"];
    
    [_titleButton setTitleForNormal:[NSString stringWithFormat:CAT_FORMAT_TEXT,catName]];
    [_dataSource fetchSmallCatWithCatId:catId];    
}

- (void)selectSmallCatFinished:(NSInteger)catId
{
    for (NSMutableDictionary *dic in _dataSource.smallCatList) {
        NSString *_catId = [dic objectForKey:@"lbid"];
        
        if ([_catId isEqualToString:INT_TO_STR(catId)]) {
            [dic setObject:@"1" forKey:@"selected"];
            continue;
        }
        [dic setObject:@"0" forKey:@"selected"];
    }
    
    [_leftTable reloadData];
    [_dataSource fetchDishWithSmallCatId:INT_TO_STR(catId)];
}

- (void)selectDishCountFinished
{
    int totalCount = 0;
    float totalMoney = 0;
    
    //获取每个分类下的菜品选择数量，将已经选择了的加入_selectedDishList数组中
    for (NSString *catId in [_dataSource.dishCache allKeys]) {
        NSMutableArray *dishList = [_dataSource.dishCache objectForKey:catId];
        
        int catCount = 0;
        for (NSDictionary *dic in dishList) {
            int count = [[dic objectForKey:@"fenshu"] intValue];
            catCount += count;

            [self updateDishCount:dic];
        }
        
        //遍历缓存获取第一级分类的id
        for (NSString *bcatId in [_dataSource.smallCatCache allKeys]) {
            
            //获取该一级分类下所有二级分类列表
            NSMutableArray *catList = [_dataSource.smallCatCache objectForKey:bcatId];
            
            //遍历二级分类列表，找到当前循环中菜品列表所属的二级分类，并设置所选的菜品数量
            for (NSMutableDictionary *dic in catList) {
                if ([[dic objectForKey:@"lbid"] isEqualToString:catId]) {
                    [dic setObject:INT_TO_STR(catCount) forKey:@"count"];
                    break;
                }
            }
        }
    }
    
    NSMutableArray *removeList = [NSMutableArray array];
    for (NSDictionary *dic in _selectedDishList) {
        int count = [[dic objectForKey:@"fenshu"] intValue];
        float money = [[dic objectForKey:@"price"] floatValue];
        
        totalCount += count;
        totalMoney += money*count;
        
        if (count == 0) [removeList removeObject:dic];
    }
    
    for (NSDictionary *dic in removeList) {
        [_selectedDishList removeObject:dic];
    }
    
    [self.leftTable reloadData];
    self.totalCountLabel.text = [NSString stringWithFormat:@"%d道菜/",totalCount];
    self.totalMoneyLabel.text = [NSString stringWithFormat:@"￥%.0f元",totalMoney];
}

- (void)updateDishCount:(NSDictionary *)dic
{
    BOOL isExists = NO;
    int fenshu = [[dic objectForKey:@"fenshu"] intValue];
    
    NSMutableArray *removeList = [NSMutableArray array];
    for (NSMutableDictionary *dish in _selectedDishList) {
        
        NSString *cid = [dish objectForKey:@"cid"];
        if (!cid) cid = [dish objectForKey:@"id"];
        NSString *nid = [dic objectForKey:@"id"];
        
        if ([cid isEqualToString:nid]) {
            if (fenshu == 0) {
                [removeList addObject:dish];
            }else {
                [dish setObject:[dic objectForKey:@"fenshu"] forKey:@"fenshu"];
            }
            
            isExists = YES;break;
        }
    }
    
    if (!isExists && fenshu > 0) [_selectedDishList addObject:dic];
    
    for (NSDictionary *dic in removeList) {
        [_selectedDishList removeObject:dic];
    }
}

- (void)firstTotal
{
    int totalCount = 0;
    float totalMoney = 0;
    
    [_selectedDishList removeAllObjects];
   
    int catCount = 0;
    for (NSDictionary *dic in _orderDishList) {
        int count = [[dic objectForKey:@"fenshu"] intValue];
        float money = [[dic objectForKey:@"price"] floatValue];
        
        catCount += count;
        totalCount += count;
        totalMoney += money*count;
        
        if (count > 0) [_selectedDishList addObject:dic];
    }
    
    [self.leftTable reloadData];
    self.totalCountLabel.text = [NSString stringWithFormat:@"%d道菜/",totalCount];
    self.totalMoneyLabel.text = [NSString stringWithFormat:@"￥%.0f元",totalMoney];
}

- (void)tapImageWithIndex:(NSInteger)index
{
    [_photoList removeAllObjects];
    if (_photoList.count == 0) {
        for (NSDictionary *dic in _dataSource.dishList) {
            NSString *url = [dic objectForKey:@"image"];
            NSString *name = [dic objectForKey:@"name"];
            NSString *price = [NSString stringWithFormat:@"￥%@",[dic objectForKey:@"price"]];
            NSString *unit = [NSString stringWithFormat:@"/%@",[dic objectForKey:@"danwei"]];
            NSString *description = [NSString stringWithFormat:@"名称:%@  价格:%@%@",name,price,unit];
            
            MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:url]];
            photo.caption = description;
            [_photoList addObject:photo];
        }
    }
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    browser.displayNavArrows = YES;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.wantsFullScreenLayout = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    [browser setCurrentPhotoIndex:index];
    
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:nc animated:YES];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photoList.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photoList.count)
        return [_photoList objectAtIndex:index];
    return nil;
}

- (IBAction)nextAction:(id)sender
{
    if (!_isNext) {
        [AppDelegate showMessage:@"本餐厅暂时关闭在线点菜功能"];
        return;
    }
    
    if (_selectedDishList.count == 0) {
        [AppDelegate showMessage:@"您忘记选择菜品了，请先选择菜品"];
        return;
    }
    
    EditSelectedDishViewController *selectedDishListVC = [[EditSelectedDishViewController alloc] init];
    selectedDishListVC.orderId = self.orderId;
    selectedDishListVC.selectedDishList = self.selectedDishList;
    
    [self.navigationController pushViewController:selectedDishListVC animated:YES];
}

- (void)setStatus:(NSDictionary *)json
{
    NSMutableArray *data = [json objectForKey:@"data"];
    if (data.count > 0) {
        NSString *dishOff = [json objectForKey:@"dish_off"];
        
        _isNext = [dishOff intValue] == 0;
        
        if (!_isNext) {
            [_btnNext setBackgroundNormal:@"btn_enable.png"];
            [_btnNext setTitleColorNormal:[UIColor grayColor]];
        }
    }
}

@end

//=================================================================================
#pragma==============数据源实现=====================================================
//=================================================================================

@implementation EditOrderDishDataSource

#define DISH_BIT_CAT_TAG 1
#define DISH_SMALL_CAT_TAG 2

#define DISH_SMALL_TAB_TAG 11
#define DISH_LIST_TAB_TAG 12

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        _dishList = [[NSMutableArray alloc] initWithCapacity:10];
        _dishCache = [[NSMutableDictionary alloc] initWithCapacity:10];
        _smallCatList = [[NSMutableArray alloc] initWithCapacity:10];
        _smallCatCache = [[NSMutableDictionary alloc] initWithCapacity:10];
    }
    return self;
}

- (void)fetchDishCategories
{
    [SVProgressHUD showWithStatus:@"菜品分类加载中..."];

    NSString *url = [NSString stringWithFormat:API_DISH_BIT_CAT, self.viewController.shopId];
    [self get:url tag:DISH_BIT_CAT_TAG];
}

- (void)fetchSmallCatWithCatId:(NSString*)catId
{
    NSMutableArray *cat = [_smallCatCache objectForKey:catId];
    if (cat) {
        self.smallCatList = cat;
        if (_smallCatList.count > 0) {
            NSString *catId = [[_smallCatList objectAtIndex:0] objectForKey:@"lbid"];
            for (NSDictionary *dic in _smallCatList) {
                if ([[dic objectForKey:@"selected"] intValue] == 1) {
                    catId = [dic objectForKey:@"lbid"];
                    break;
                }
            }
            
            [self fetchDishWithSmallCatId:catId];
        }
        
        [_viewController.leftTable reloadData];
        return;
    }
    
    NSString *url = [NSString stringWithFormat:API_DISH_SMALL_CAT, self.viewController.shopId,catId];
    [self get:url tag:DISH_SMALL_CAT_TAG];
}

- (void)fetchDishWithSmallCatId:(NSString*)catId
{
    NSMutableArray *dish = [_dishCache objectForKey:catId];
    if (dish) {
        self.dishList = dish;
        [_viewController.rightTable reloadData];
        [_viewController.rightTable scrollRectToVisible:TOP_LOCATION animated:YES];
        return;
    }
    
    [SVProgressHUD showWithStatus:@"菜品数据加载中..."];
    NSString *url = [NSString stringWithFormat:API_DISH_DISH_LIST, self.viewController.shopId,catId];
    [self get:url tag:DISH_LIST_TAB_TAG];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSDictionary *json = [request.responseData JSONValue];
    if ([[json objectForKey:@"error_code"] intValue] != 0) {
        return;
    }
    
    if (request.tag == DISH_BIT_CAT_TAG) {        
        [_viewController setStatus:json];
        
        NSMutableArray *data = [json objectForKey:@"data"];
        _viewController.selectCategoriesView.categoriesList = data;
        [_viewController.selectCategoriesView tableViewSelectRowForCatId:_viewController.dishCatId];
    }
    
    if (request.tag == DISH_SMALL_CAT_TAG) {
        [SVProgressHUD dismiss];
        
        self.smallCatList = [json objectForKey:@"data"];
        if (self.smallCatList.count > 0) {
            for (NSMutableDictionary *dic in self.smallCatList) {
                [dic setObject:@"0" forKey:@"selected"];
            }
            
            NSMutableDictionary *dic = [self.smallCatList objectAtIndex:0];
            [dic setObject:@"1" forKey:@"selected"];
            
            NSString *catId = [dic objectForKey:@"lbid"];
            NSString *bcatId = [json objectForKey:@"fenlei"];
            
            [self fetchDishWithSmallCatId:catId];
            
            [_smallCatCache setObject:_smallCatList forKey:bcatId];
        }
        
        [self updateDishCat:_smallCatList];
        [_viewController firstTotal];
    }
    
    if (request.tag == DISH_LIST_TAB_TAG) {
        [SVProgressHUD dismiss];
        
        NSString *catId = [json objectForKey:@"lbid"];
        self.dishList = [json objectForKey:@"dish"];
        
        for (NSMutableDictionary *dic in self.dishList) {
            [dic setObject:@"0" forKey:@"fenshu"];
        }
        
        [self updateDish:_dishList];
        [_dishCache setObject:_dishList forKey:catId];

        [_viewController.rightTable reloadData];
        [_viewController.rightTable scrollRectToVisible:TOP_LOCATION animated:YES];
    }
}

- (void)updateDishCat:(NSMutableArray *)dishCat
{
    for (NSMutableDictionary *dic in dishCat) {
        NSString *lbid = [dic objectForKey:@"lbid"];
        NSMutableDictionary *n_dic = [self findDishCatById:lbid];
        if (n_dic) {
            [dic setObject:[n_dic objectForKey:@"count"] forKey:@"count"];
        }
    }
}

- (NSMutableDictionary *)findDishCatById:(NSString *)lbid
{
    for (NSMutableDictionary *dic in _viewController.orderDishCatList) {
        NSString *n_lbid = [dic objectForKey:@"lbid"];
        if ([n_lbid isEqualToString:lbid]) {
            return dic;
        }
    }
    return nil;
}

- (void)updateDish:(NSMutableArray *)dish
{
    for (NSMutableDictionary *dic in dish) {
        NSString *cid = [dic objectForKey:@"id"];
        NSMutableDictionary *n_dic = [self findDishByCid:cid];
        if (n_dic) {
            NSString *fenshu = [NSString stringWithFormat:@"%@",[n_dic objectForKey:@"fenshu"]];
            [dic setObject:fenshu forKey:@"fenshu"];
        }
    }
}

- (NSMutableDictionary *)findDishByCid:(NSString *)cid
{
    for (NSMutableDictionary *dic in _viewController.orderDishList) {
        NSString *n_cid = [dic objectForKey:@"cid"];
        if ([n_cid isEqualToString:cid]) {
            return dic;
        }
    }
    return nil;
}

#pragma ===================加载tableview数据 Begin=============================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return tableView.tag == DISH_SMALL_TAB_TAG ? 41 : 78;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return tableView.tag == DISH_SMALL_TAB_TAG ? _smallCatList.count : _dishList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == DISH_SMALL_TAB_TAG) {
        static NSString *CellId = @"SelectDishLeftCell";
        
        SelectDishLeftCell *cell = [_viewController createCellWithNib:CellId tableview:tableView];
        cell.delegate = self.viewController;
        [Functions disabledDelaysContentTouches:cell];
        
        NSDictionary *dic = [self.smallCatList objectAtIndex:indexPath.row];
        [cell setContent:dic];
        
        return cell;
    }
    
    if (tableView.tag == DISH_LIST_TAB_TAG) {
        static NSString *CellId = @"SelectDishRightCell";
        
        SelectDishRightCell *cell = [_viewController createCellWithNib:CellId tableview:tableView];
        cell.delegate = self.viewController;
        [Functions disabledDelaysContentTouches:cell];
        
        NSMutableDictionary *dic = [self.dishList objectAtIndex:indexPath.row];
        [cell setContent:dic andIndex:indexPath.row];
        
        return cell;
    }
    
    return nil;
}

@end

#pragma=============================================================================
//======================下拉菜单=====================================================
#pragma=============================================================================

@implementation EditOrderDishCategoriesView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self) {
        self.hidden = YES;
        [self setBackgroundColor:[UIColor clearColor]];
        [self drawCornerRadius];
        
        _categoriesList = [[NSMutableArray alloc] initWithCapacity:5];
        
        _backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [_backImage setImage:[UIImage imageNamed:@"dropbox_bg.png"]];
        _backImage.userInteractionEnabled = YES;
        [_backImage drawCornerRadius];
        [self addSubview:_backImage];
        
        _categoriesTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, frame.size.width, frame.size.height-10)];
        [_categoriesTable setBackgroundColor:[UIColor clearColor]];
        _categoriesTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _categoriesTable.bounces = NO;
        _categoriesTable.delegate = self;
        _categoriesTable.dataSource = self;
        [_categoriesTable drawCornerRadius];
        [_backImage addSubview:_categoriesTable];
    }
    
    return self;
}

- (void)showOrVisible
{
    [self.categoriesTable reloadData];
    [self.categoriesTable autoHeight];
    [self.backImage autoHeight];
    
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.hidden = !self.hidden;
        self.top = !self.hidden ? (DeviceSystemVersion < SystemVersion_7_0 ? 0 : 64) : (0-self.categoriesTable.height);
        
        [self autoHeight];
        if (self.height < 80) {
            self.height = 80;
            self.backImage.height = 80;
        }
    } completion:^(BOOL finished){
        
    }];
}

#pragma ===================加载tableview数据 Begin=============================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _categoriesList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell123";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell setBackgroundColor:[UIColor clearColor]];
    }
    
    NSDictionary *dic = [_categoriesList objectAtIndex:indexPath.row];
    
    cell.textLabel.text = [dic objectForKey:@"lbname"];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 40, tableView.frame.size.width, 1)];
    line.image = [UIImage imageNamed:@"dropbox_line.png"];
    
    [cell addSubview:line];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_delegate) {
        NSDictionary *dic = [_categoriesList objectAtIndex:indexPath.row];
        [_delegate selectDishCatFinished:dic];
        [self showOrVisible];
    }
}

- (void)tableViewSelectRowForCatId:(NSString *)catId
{
    int rowIndex = 0;
    NSDictionary *dic = [self findCat:catId];
    if (dic) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[_categoriesList indexOfObject:dic] inSection:0];
        rowIndex = indexPath.row;
    }
    
    if (_delegate) {
        NSDictionary *dic = [_categoriesList objectAtIndex:rowIndex];
        [_delegate selectDishCatFinished:dic];
    }
}

- (NSDictionary *)findCat:(NSString *)catId
{
    for (NSDictionary *dic in _categoriesList) {
        NSString *cid = [dic objectForKey:@"id"];
        if ([cid isEqualToString:catId]) {
            return dic;
        }
    }
    return nil;
}

@end
